package com.nopay.dxdwphone.ui.fragment;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;

import androidx.recyclerview.widget.LinearLayoutManager;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nopay.dxdwphone.base.BaseFragment;
import com.nopay.dxdwphone.bean.CommonResponse;
import com.nopay.dxdwphone.bean.request.DeleteCallTaskFromGroupRequest;
import com.nopay.dxdwphone.bean.request.GetCallTaskUnCallRequest;
import com.nopay.dxdwphone.bean.request.SaveCallDataRequest;
import com.nopay.dxdwphone.bean.response.GetCallTaskCallResponse;
import com.nopay.dxdwphone.bean.response.SaveCallDataResponse;
import com.nopay.dxdwphone.dialog.DialogClearCallLog;
import com.nopay.dxdwphone.dialog.DialogPleaseOpenCallSetting;
import com.nopay.dxdwphone.dialog.DialogWaitCallTransferSetting;
import com.nopay.dxdwphone.receiver.PhoneBroadcastReceiver;
import com.nopay.dxdwphone.utils.CallLogHelper;
import com.nopay.dxdwphone.utils.CallTransferUtil;
import com.nopay.dxdwphone.utils.MemberManager;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.SinaRefreshView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.nopay.dxdwphone.CallGroupEnum;
import com.nopay.dxdwphone.Constants;
import com.nopay.dxdwphone.R;
import com.nopay.dxdwphone.databinding.FragmentCallLogBinding;

import com.nopay.dxdwphone.ui.adapter.CallLogAdapter;
import com.nopay.dxdwphone.ui.ativity.MainActivity;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CallLogFragment extends BaseFragment<FragmentCallLogBinding> {

    private CallLogAdapter adapter;
    private List<GetCallTaskCallResponse.Data> dataList = new ArrayList<>();
    private int page = 1;

    @Override
    protected void loadData() {
        binding.rlRoot.setPadding(0, getStatusBarHeight(getActivity()), 0, 0);

        // 添加头
        SinaRefreshView headerView = new SinaRefreshView(getActivity());
        headerView.setArrowResource(R.mipmap.arrow);
        headerView.setTextColor(0xff745D5C);
        binding.refreshCallLog.setHeaderView(headerView);
        // 添加底
        com.lcodecore.tkrefreshlayout.footer.LoadingView loadingView = new com.lcodecore.tkrefreshlayout.footer.LoadingView(getActivity());
        binding.refreshCallLog.setBottomView(loadingView);

        binding.rvCallLog.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new CallLogAdapter(dataList);
        adapter.setOnItemChildClickListener((baseAdapter, view, position) -> {
            if(view.getId() == R.id.iv_dialed) {
                // TODO 拨号
                if(!MemberManager.hasMemberPermission()) {
                    if(!MemberManager.hasFreeTimes()) {
                        ToastUtils.showShort("今日免费次数已用完");

//                        new DialogPleaseOpenMember(getActivity()).setOnOpenMemberConfirmListener(() -> {
//                            ((MainActivity) getActivity()).gotoRecharge();
//                        }).show();
                        return;
                    }
                }

                if(!SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false)) {
                    new DialogPleaseOpenCallSetting(getActivity()).setOnOpenCallSettingConfirmListener(() -> {
                        // TODO 开启防封设置
                        ((MainActivity) getActivity()).gotoCallSetting();
                    }).show();
                    return;
                }

                MemberManager.addUseTimes();

                GetCallTaskCallResponse.Data bean = adapter.getItem(position);
//                initCallFinishListener(bean);
//
//                if(CallTransferUtil.open(getActivity(), bean.getCalledNumber())) {
//                    new DialogWaitCallTransferSetting(getActivity())
//                            .setOnWaitFinishListener(() -> CallTransferUtil.call(getActivity(), ""))
//                            .show(SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TIME_OUT, Constants.CALL_TRANSFER_DEFAULT_TIME_OUT));
//                } else {
//                    CallTransferUtil.call(getActivity(), bean.getCalledNumber());
//                }

                if(CallTransferUtil.open(getActivity(), bean.getCalledNumber())) {
                    if(SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                        initDianXinCallFinishListener(bean);
                    } else {
                        initCallFinishListener(bean);
                        new DialogWaitCallTransferSetting(getActivity())
                                .setOnWaitFinishListener(() -> CallTransferUtil.call(getActivity(), ""))
                                .show(SPUtils.getInstance().getInt(Constants.SP_CALL_TRANSFER_TIME_OUT, Constants.CALL_TRANSFER_DEFAULT_TIME_OUT));
                    }
                } else {
                    initCallFinishListener(bean);
                    CallTransferUtil.call(getActivity(), bean.getCalledNumber());
                }
            }

            if(view.getId() == R.id.iv_copy) {
                // TODO 复制
                ClipboardUtils.copyText(adapter.getItem(position).getCalledNumber());
                ToastUtils.showShort("手机号复制成功");
                try {
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                    ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                    intent.addCategory(Intent.CATEGORY_LAUNCHER);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setComponent(cmp);
                    mActivity.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    ToastUtils.showShort("检查到您手机没有安装微信，请安装后使用该功能");
                }
            }
        });
        binding.rvCallLog.setAdapter(adapter);

        binding.refreshCallLog.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                // TODO 刷新
                page = 1;
                dataList.clear();

                requestCallLogData(() -> {
                    refreshLayout.finishRefreshing();
                    adapter.notifyDataSetChanged();
                });
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                // TODO 加载更多
                requestCallLogData(() -> {
                    refreshLayout.finishLoadmore();
                    adapter.notifyDataSetChanged();
                });
            }
        });

        // 开始加载数据
//        binding.refreshCallLog.startRefresh();

        binding.tvClear.setOnClickListener(view -> {
            // TODO 清空当前通话记录
            if(dataList.size() == 0) {
                ToastUtils.showShort("当前无通话记录");
                return;
            }

            new DialogClearCallLog(getActivity()).setOnClearCallLogConfirmListener(() -> {
                // TODO 确认清空
                DeleteCallTaskFromGroupRequest bean = new DeleteCallTaskFromGroupRequest();
                bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
                bean.setType(1);

                RequestBody body = getRequestBody(bean);
                api.doDeleteCallTaskFromGroup(body).enqueue(new Callback<CommonResponse>() {
                    @Override
                    public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                        if (response.body() != null) {
                            if (Constants.RESULT_OK.equals(response.body().getCode())) {
                                ToastUtils.showShort("删除成功");
                                binding.refreshCallLog.startRefresh();
                            } else {
                                ToastUtils.showShort(response.body().getMsg());
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResponse> call, Throwable t) {
                        ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                    }
                });
            }).show();
        });

        binding.btnExport.setOnClickListener(view -> {
            // TODO 通话记录导出
            ((MainActivity) getActivity()).gotoCallLogExport();
        });
    }

    public void refreshData() {
        if(binding != null) binding.refreshCallLog.startRefresh();
    }

    private void requestCallLogData(OnRequestDataCompleteCallback callback) {
        callback.onComplete();

        String phone = SPUtils.getInstance().getString(Constants.SP_PHONE, "");
        GetCallTaskUnCallRequest request = new GetCallTaskUnCallRequest();
        request.setPhone(phone);
        request.setPageNum(page);
        request.setPageSize(50);

        RequestBody body = getRequestBody(request);
        api.doGetCallLogList(body).enqueue(new Callback<GetCallTaskCallResponse>() {
            @Override
            public void onResponse(Call<GetCallTaskCallResponse> call, Response<GetCallTaskCallResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        List<GetCallTaskCallResponse.Data> callTaskList = response.body().getRows();
                        if(callTaskList != null && callTaskList.size() > 0) {
                            dataList.addAll(callTaskList);
                            page++;
                        }
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }

                callback.onComplete();
            }

            @Override
            public void onFailure(Call<GetCallTaskCallResponse> call, Throwable t) {
                callback.onComplete();
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
            }
        });
    }

    public interface OnRequestDataCompleteCallback {

        void onComplete();
    }

    public void initDianXinCallFinishListener(GetCallTaskCallResponse.Data callInfo) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> {
            if(status == 1) {
                new Handler().postDelayed(() -> {
                    initCallFinishListener(callInfo);
                    CallTransferUtil.call(getActivity(), "");
                }, 100);
            }
        });
    }

    public void initCallFinishListener(final GetCallTaskCallResponse.Data callInfo) {
        PhoneBroadcastReceiver.setOnCallFinishListener((status, callLogItem) -> new Thread(() -> {
//            CallLogHelper.CallLogItem callLogItem = getCallLog(2);
            if(status == 1) {
                if(callLogItem != null) {
                    // 保存通话记录
                    saveCallData(callInfo, callLogItem.getDate(), callLogItem.getDuration(), 0);
                } else {
                    // 保存通话记录
                    @SuppressLint("SimpleDateFormat") String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    saveCallData(callInfo, dateStr, 0, 0);
                }

                if(!SPUtils.getInstance().getBoolean(Constants.SP_SIM_TELECOM, false)) {
                    boolean isOpen = SPUtils.getInstance().getBoolean(Constants.SP_ENABLED_CALL_TRANSFER, false);
                    if(isOpen && getActivity() != null && !getActivity().isFinishing()) CallTransferUtil.close(getActivity());
                }
            }
        }).start());
    }

    private CallLogHelper.CallLogItem getCallLog(int times) {
        CallLogHelper.CallLogItem callLogItem = CallLogHelper.fetchNewCallLog(getContext());
        if(callLogItem == null) {
            if(times > 0) {
                times--;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return getCallLog(times);
            }
        }
        return callLogItem;
    }

    public void saveCallData(final GetCallTaskCallResponse.Data callInfo, final String dateStr, final int duration, final int saveTimes) {
        SaveCallDataRequest bean = new SaveCallDataRequest();
        bean.setCallDate(dateStr);
        bean.setCalledNumber(callInfo.getCalledNumber());
        String callingNumber = CallTransferUtil.getPhoneNumberByCallSetting();
        bean.setCallingNumber("".equals(callingNumber) ? "未知" : callingNumber);
        bean.setCompany(callInfo.getCompany());
        bean.setDuration(duration);
        bean.setName(callInfo.getName());
        bean.setPhone(SPUtils.getInstance().getString(Constants.SP_PHONE, ""));
        bean.setStatus(duration > 0 ? 1 : 2);
        bean.setTaskId(CallGroupEnum.IMPORT_MANUAL.getGroupId());

        RequestBody body = getRequestBody(bean);
        api.doSaveCallData(body).enqueue(new Callback<SaveCallDataResponse>() {
            @Override
            public void onResponse(Call<SaveCallDataResponse> call, Response<SaveCallDataResponse> response) {
                if (response.body() != null) {
                    if (Constants.RESULT_OK.equals(response.body().getCode())) {
                        ToastUtils.showShort("通话记录已保存");
                        binding.refreshCallLog.startRefresh();
                        return;
                    } else {
                        ToastUtils.showShort(response.body().getMsg());
                    }
                }
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(callInfo, dateStr, duration, saveTimes + 1), 3000);
            }

            @Override
            public void onFailure(Call<SaveCallDataResponse> call, Throwable t) {
                ToastUtils.showShort(getActivity().getResources().getString(R.string.call_api_error));
                if(saveTimes < 3) new Handler().postDelayed(() -> saveCallData(callInfo, dateStr, duration, saveTimes + 1), 3000);
            }
        });
    }
}
